package serverapp

import (
	"net/http"
	"time"

	"github.com/micro/go-micro/registry"
	"github.com/micro/go-micro/registry/mdns"
	"github.com/micro/go-micro/registry/memory"
	"github.com/micro/go-micro/web"
	"github.com/micro/go-plugins/registry/consul"
	"github.com/micro/go-plugins/registry/gossip"
)

//WebService webserver包装和实现
type WebService interface {
	Client() *http.Client
	Init(opts ...Option) error
	Handle(pattern string, handler http.Handler)
	HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
	Run() error
}

//baseService 数据
type webService struct {
	w    web.Service
	opts Options
}

//NewWebService 申请一个machineservice服务
func NewWebService() WebService {
	return &webService{
		w: nil,
	}
}

//Init 初始化
func (ws *webService) Init(opts ...Option) error {

	for _, o := range opts {
		o(&ws.opts)
	}
	// 创建web服务
	ws.w = web.NewService(
		web.Name(ws.opts.webCfg.SrvName),
		web.Context(ws.opts.context),
		web.Address(ws.opts.webCfg.Addr),
		web.Version(ws.opts.webCfg.Version),
		web.Registry(ws.NewRegistry(ws.opts.webCfg.Registry)),
		web.RegisterTTL(time.Second*time.Duration(ws.opts.webCfg.TTL)),
		web.RegisterInterval(time.Second*time.Duration(ws.opts.webCfg.Interval)),
	)

	return nil
}

func (ws *webService) NewRegistry(rn string) registry.Registry {
	switch rn {
	case "consul":
		return consul.NewRegistry()
	case "gossip":
		return gossip.NewRegistry()
	case "memory":
		return memory.NewRegistry()
		//"mdns"
	default:
		return mdns.NewRegistry()
	}
}

func (ws *webService) Client() *http.Client {
	return ws.w.Client()
}

//Run 运行
func (ws *webService) Run() error {
	if err := ws.w.Run(); err != nil {
		return err
	}
	return nil
}

func (ws *webService) Handle(pattern string, handler http.Handler) {
	ws.w.Handle(pattern, handler)
}
func (ws *webService) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
	ws.w.HandleFunc(pattern, handler)
}
